package com.guli.edu.controller;

import com.alibaba.fastjson.JSON;
import com.guli.common.constant.AuthServerConstant;
import com.guli.common.constant.WebSiteConstant;
import com.guli.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/*
 * @Author 罗
 * @date 2020/10/20 - 3:01 下午
 */
@RestController
@CrossOrigin
@Slf4j
public class EduController {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    /**
     * 无需登陆就能访问
     *
     * @return
     */
    @GetMapping("/hello")
    public R hello() {
        return R.ok().putMsg("同学你好呀");
    }

    /**
     * 登陆之后才能访问
     */
    @GetMapping("getEmployeeList")
    public R getEmployeeList(HttpSession session, @RequestParam(value = "token", required = false) String token, HttpServletRequest request, HttpServletResponse response) {

        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER_SESSION);

        /**
         * 有token说明是从 authentication 服务器 认证之后得到的结果
         * */
        if (!ObjectUtils.isEmpty(token)) {
            String tokenUserInfo = stringRedisTemplate.opsForValue().get(token);
            log.info("当前认证的用户是{}", tokenUserInfo);
            if (ObjectUtils.isEmpty(tokenUserInfo)) {
                /**
                 * 用户的 token 无效（重新认证）
                 * */

                log.info("用户的 token = {} 无效（重新认证）", token);

                return R.redirect(WebSiteConstant.PRE_AUTH_JUDGE_CONTROLLER, WebSiteConstant.CLIENT_2 + "/index.html");

            }
        }

        if (ObjectUtils.isEmpty(attribute) && ObjectUtils.isEmpty(token)) {

            log.info("当前用户没有查询到session = {}，也没有token ={}，跳转认证服务", attribute, token);

            /**
             * 去认证
             * */
            //return String.format("redirect:%s", WebSiteConstant.AUTH_WEB_PAGE);
            return R.redirect(WebSiteConstant.PRE_AUTH_JUDGE_CONTROLLER, WebSiteConstant.CLIENT_2 + "/index.html");

            // 这样登陆之后直接跳转这个 controller 可以直接成功
            // return R.redirect(WebSiteConstant.AUTH_WEB_PAGE, WebSiteConstant.MAIN_DOMAIN + ":60001/getEmployeeList");

        }

        log.info("用户通过验证，即将查询数据");

        List<String> empList = new ArrayList<>();

        empList.add("小高");

        empList.add("小罗");

        //return JSON.toJSONString(empList);
        return R.ok().put("EmployeeList", empList);
    }
}
